<template>
    <div>
      <!--面包屑导航区-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片视图-->
      <el-card>
        <!--搜索与添加区域-->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!--用户列表区-->
        <el-table stripe border :data="userList" style="width: 100%">
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="nickname" label="昵称"></el-table-column>
          <el-table-column prop="phoneNumber" label="电话"></el-table-column>
          <el-table-column prop="birthday" label="生日"></el-table-column>
          <el-table-column prop="cTime" label="创建时间"></el-table-column>
          <el-table-column prop="enabled" label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enabled" @change="userStateChanged(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-tooltip effect="dark" :enterable="false" content="修改" placement="top">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :enterable="false" content="删除" placement="top">
                <el-button type="danger" size="mini" @click="removeUserById(scope.row.id)" icon="el-icon-delete"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :enterable="false" content="分配角色" placement="top">
                <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--分页区域-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[2,4,6,8]"
          :page-size="queryInfo.pageSize"
          :total="total"
          layout="total,sizes,prev,pager,next,jumper">
        </el-pagination>
        <!--添加用户的对话框-->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
          <!--内容主体区域 ref引用名称-->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="addForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
          </el-form>
          <!--底部按钮区域-->
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
        </el-dialog>
        <!--修改用户的对话框-->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
          <!--内容主体区域 ref引用名称-->
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="editForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
          </el-form>
          <!--底部按钮区域-->
          <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
</template>

<script>
export default {
  data () {
    // 自定义验证规则: 邮箱的规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regPhone = /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regPhone.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 2
      },
      userList: [],
      total: 0,
      // 控制用户添加对话框
      addDialogVisible: false,
      // 添加用户的表单信息
      addForm: {
        username: '',
        password: '',
        email: '',
        nickname: '',
        phoneNumber: ''
      },
      // 添加用户的校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名的长度在2~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码的长度在6~16个字符之间', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制修改用户的对话框
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 修改用户的校验规则
      editFormRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '昵称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('/vueShop/users', { params: this.queryInfo })
      // console.log(res)
      if (!res.status) return this.$message.error(res.msg)
      res.data.forEach((item, index, arr) => {
        item.enabled = item.enabled === 'true'
      })
      this.userList = res.data
      this.total = res.total
    },
    // 监听 pageSize 改变的事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    // 监听 switch 用户状态改变函数
    async userStateChanged (userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(`/vueShop/users/${userInfo.id}/enabled/${userInfo.enabled}`)
      if (!res.status) {
        userInfo.enabled = !userInfo.enabled
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        // 发起添加用户的真正请求
        const { data: res } = await this.$http.post('/vueShop/users?username=' + this.addForm.username +
          '&password=' + this.addForm.password + '&email=' + this.addForm.email + '&nickname=' +
          this.addForm.nickname + '&phoneNumber=' + this.addForm.phoneNumber)
        if (!res.status) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 点击展示编辑用户的对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('/vueShop/users/' + id)
      if (!res.status) return this.$message.error('查询用户详细数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击修改用户
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证不通过')
        // const { data: res } = await this.$http.put('/vueShop/users/' + this.editForm.id, {
        //   email: this.editForm.email,
        //   nickname: this.editForm.nickname,
        //   phoneNumber: this.editForm.phoneNumber
        // })
        // 发起修改用户的真正请求
        const { data: res } = await this.$http.put('/vueShop/users/' + this.editForm.id +
          '?email=' + this.editForm.email + '&nickname=' + this.editForm.nickname +
          '&phoneNumber=' + this.editForm.phoneNumber)
        if (!res.status) return this.$message.error('修改用户失败')
        this.$message.success('修改用户成功')
        // 隐藏添加用户的对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 点击就删除角色
    async removeUserById (id) {
      // 这样就不需要加 async 和 await
      /*
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      */
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认删除 confirm 取消异常 cancel
      if (confirmResult !== 'confirm') return this.$message.info('用户取消了删除')
      const { data: res } = await this.$http.delete('/vueShop/users/' + id)
      if (!res.status) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>

</style>
